﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace QAQ
{
    class SocServer
    {
        static TcpListener listener=null;
        static GCPacket mGCPacket = null;
        
        const int LIMIT = 5; //1 concurrent clients
        Thread[] mThreads = new Thread[LIMIT];


        public SocServer(GCPacket GCP,int Port)
        {
            listener = new TcpListener(Port);
            listener.Start();
            mGCPacket = GCP;
            
            for (int i = 0; i < LIMIT; i++)
            {
                mThreads[i] = new Thread(new ThreadStart(Service));
                mThreads[i].Start();                
            }
        }
        public void Dispose()
        {
            listener.Stop();
            for (int i = 0; i < LIMIT; i++)
            {
                mThreads[i].Interrupt(); 
                mThreads[i].Abort();                
            }
        }
        
        public static void Service()
        {
            while (true)
            {
                Socket soc;
                try
                {
                    soc= listener.AcceptSocket();
                }
                catch (Exception e)
                {
                    return;
                }
                //soc.SetSocketOption(SocketOptionLevel.Socket,
                //        SocketOptionName.ReceiveTimeout,10000);
                try
                {
                    Stream s = new NetworkStream(soc);
                    StreamReader sr = new StreamReader(s);
                    StreamWriter sw = new StreamWriter(s);
                    sw.AutoFlush = true; // enable automatic flushing
                                                
                    while (true)
                    {                        
                        switch(sr.ReadLine())
                        {
                            case "ROOMID?":
                                sw.WriteLine(mGCPacket.GetId().ToString());
                            break;
                            case "PASSWD?":
                                sw.WriteLine(mGCPacket.mStringPasswd);
                            break;
                            case "BADASS":
                            Form1.mBadass = true;
                            break;
                            default:
                            break;
                        }
                    }
                    s.Close();
                }
                catch (Exception e)
                {
              //      MessageBox.Show(e.ToString());
                }
                soc.Close();
            }            
        }
    }
}
